//实现对整形数据的排序，将排序后的数据存储到新的文件中，并输出排序的结果
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>

#define PATH_NAME "./int.info"

typedef struct INTDATA
{
    int a;
    struct INTDATA *next;
}IDA;
typedef struct List
{
    int LLen;
	IDA *pFirstNode;
}List;
//申请空间
IDA *mkdirIDA()
{
    IDA *shu=(IDA*)malloc(sizeof(IDA));
    if(NULL == shu)
    {
        exit(EXIT_FAILURE);
    }
    else
    {
        memset(shu,0,sizeof(IDA));
    }
    return shu;
}
//申请空间
List *mkdirList()
{
    List *list=(List*)malloc(sizeof(List));
    if(NULL == list)
    {
        exit(EXIT_FAILURE);
    }
    else
    {
        memset(list,0,sizeof(List));
    }
    return list;
}
//插入数据，生成链表
void insert(List *list, IDA *node)
{
	if (NULL == list || NULL == node)
	{
		return;
	}
	node->next = list->pFirstNode;
	list->pFirstNode = node;	
	list->LLen++;
}
//排序
void MySort(List *list)
{
	if (NULL == list)
	{
		return;
	}
	IDA *pre = NULL;
	IDA *cur = NULL;
	int i=0;
	int j=0;
	for (; i<list->LLen; i++)
	{
		pre = list->pFirstNode;
		cur = pre;
		for (j=0; j<list->LLen-1; j++)
		{
			if (cur->a > cur->next->a)
			{
				if (cur == list->pFirstNode)
				{
					list->pFirstNode = cur->next;	
					cur->next = cur->next->next;
					list->pFirstNode->next = cur;
					pre = list->pFirstNode;
					continue;
				}
				else
				{
					pre->next = cur->next;
					cur->next = cur->next->next;	
					pre->next->next = cur;
					pre = pre->next;
					continue;
				}
			}	
			pre = cur;
			cur = cur->next;
		}
	}
}
//输入信息
void myInput(IDA *shu)
{
    if(NULL != shu)
    {
        printf("请输入整数，或输入99099退出:\n");
        scanf("%d",&shu->a);
    }
}
//输出
void display(const List *list)
{
	if (NULL == list)
	{
		return;
	}

	IDA *node = list->pFirstNode;
	while (NULL != node)
	{
		printf("%d\t",node->a);
		node = node->next;
	}
	printf("\n");
}
//将数据保存到文件中
void saveListToFile(const char *path,const List *list)
{
    if(NULL == path || NULL == list)
    {
        return;
    }
    FILE *file=fopen(path,"wb");
    IDA *node=list->pFirstNode;
    while(NULL != node)
    {
        fwrite(node,sizeof(IDA),1,file);
        node=node->next;
    }
    fclose(file);
}
int main(void)
{
	List *intlist=mkdirList();
	IDA *node=NULL;
	while(1)
	{
		node=mkdirIDA();
		myInput(node);
		if(99099 == node->a)
		{
			free(node);
			node=NULL;
			break;
		}
		insert(intlist,node);
	}
	display(intlist);
	MySort(intlist);
	display(intlist);
	saveListToFile(PATH_NAME,intlist);
	printf("数据已保存在%s中\n",PATH_NAME);
	return 0;
}